﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business.Project;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Project;
using AMM.UserControls;

namespace AMM.Forms.Project {
    public partial class FrmMould : FrmMouldBase {

        private int _pageIndex;
        private MouldSearchModel _searchModel;
        private MouldProcessor _mouldProcessor;
        private List<MouldViewModel> _mouldList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1311"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new MouldSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new Mould() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<MouldViewModel> selectedList = this.dgvMouldList.GetSelectedRows<MouldViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            Mould mould = this._mouldProcessor.FetchMouldById(selectedList[0].Key);
            mould.ClassStatus = ClassStatus.Updated;
            this.ShowEditForm("修改", mould);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<MouldViewModel> selectedList = this.dgvMouldList.GetSelectedRows<MouldViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._mouldProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new MouldSearchModel();
                }
                else {
                    this._searchModel = (MouldSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindMouldList();
            });
        }

        #endregion

        public FrmMould() {
            InitializeComponent();

            this.dgvMouldList.DataGridViewModelType = typeof(MouldViewModel);
            this.dgvMouldDetailList.DataGridViewModelType = typeof(MouldDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            Mould mould = (Mould)e.EditModel;
            if (mould.MouldDetails.Count == 0) {
                this.ShowError("请添加物料明细记录！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (mould.ClassStatus == ClassStatus.Added) {
                    mould.CreatedBy = LoginUserName;
                    this._mouldProcessor.Insert(mould);
                }
                else {
                    mould.ModifiedBy = LoginUserName;
                    this._mouldProcessor.Update(mould);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindMouldList();
            this.BindMouldDetailsList(0);
        }

        private void BindMouldList() {
            this.CreateNewThread(() => {
                this._mouldList = this._mouldProcessor.FetchMouldViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvMouldList.DataSource = new SortableBindingList<MouldViewModel>(this._mouldList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindMouldDetailsList(int mouldId) {
            List<MouldDetailsViewModel> detailsList = new List<MouldDetailsViewModel>();
            this.CreateNewThread(() => {
                if (mouldId != 0) {
                    detailsList = this._mouldProcessor.FetchMouldDetailsViewModelList(mouldId);
                }
            }, () => {
                this.dgvMouldDetailList.DataSource = new SortableBindingList<MouldDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, Mould mould) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                MouldEditControl editControl = new MouldEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = mould;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmMould_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._mouldProcessor = new MouldProcessor(this.pceList.PageSize);
                this._searchModel = new MouldSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindMouldList();
        }

        private void dgvMouldList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvMouldList.CurrentRow != null) {
                int mouldId = (int)this.dgvMouldList.CurrentRow.Cells["Key"].Value;
                this.BindMouldDetailsList(mouldId);
            }
        }

    }
}
